﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Text;
using SCSService;
using SCS.Core.Models;
using SCS.Core.ViewModels;

namespace SCS.Core.Controllers
{
    public class UserController : BaseController
    {
        static string olUrl;

        public ActionResult Index()
        {
            return RedirectToAction("ListUsers");
        }

        public ActionResult SignIn()
        {

            return View();
        }

        [HttpPost]
        public ActionResult SignIn(FormCollection values)
        {
            string olUrl = Request.UrlReferrer.AbsoluteUri;

            var Login = new Models.Collection.LoginCollection();
            TryUpdateModel(Login);
            int siteGuid = GetSiteGuid();

            try
            {

                int idLogin = Models.UserModel.LoginUser(Login.UserName, Login.Password) != null ? Models.UserModel.LoginUser(Login.UserName, Login.Password).UserID : 0;
                if (idLogin > 0)
                {
                    if (Login.Remember)
                    {
                        HttpCookie ck = new HttpCookie("Sercurity_Uesr_Name");
                        ck.Value = Login.UserName;
                        ck.Expires = DateTime.Now.AddMonths(1);//Thoi han luu cookie
                        HttpContext.Response.Cookies.Add(ck);

                        HttpCookie ckPass = new HttpCookie("Sercurity_Uesr_Password");
                        ck.Value = Login.Password;
                        ck.Expires = DateTime.Now.AddMonths(1);//Thoi han luu cookie
                        HttpContext.Response.Cookies.Add(ckPass);
                    }

                    int roleSystem = Models.UserModel.GetRoleSystemByUser(idLogin).Priority ?? 0;

                    var roleLocal = Models.UserModel.GetRoleLocalSiteByUser(idLogin, GetSiteGuid());

                    if (roleSystem > 2 || roleLocal != null)
                    {
                        ViewData["error"] = "Bạn không đủ quyền đăng nhập.";
                        return View();
                    }
                    else
                    {
                        List<System_Website> listSite = Models.ConfigModel.GetListSiteByUserAdmin(idLogin);

                        if (listSite.Count() > 0)
                        {

                            Session["UserID"] = idLogin;
                            //int id = DefaultSiteGuidGetter();
                            Session["siteguid"] = listSite.FirstOrDefault().SiteGuid;

                            //Ghi lại log SignIn
                            SCSService.Security_User_Log log = new Security_User_Log();
                            log.UserID = idLogin;
                            log.LoginDate = DateTime.Now;

                            Session["LogID"] = Models.UserModel.CreateLog(log);

                            List<Config_Modul> listModule = ConfigModel.GetListModulforUserLogin(listSite.FirstOrDefault().SiteGuid, idLogin, 1);
                            var listModuleName = listModule.Select(p => p.ModulName).ToList();
                            if (listModuleName.Contains("HomeMaster"))
                            {
                                return Redirect("/" + listSite.FirstOrDefault().SiteGuid + "/" + DefaultLanguageGetter() + "/HomeMaster/Index");
                            }
                            else if (listModuleName.Contains("Dashboard"))
                            {
                                return Redirect("/" + listSite.FirstOrDefault().SiteGuid + "/" + DefaultLanguageGetter() + "/Dashboard/DashboardIndex");
                            }


                        }

                    }


                }
                else
                {
                    ViewData["error"] = "Sai Tên đăng nhập hoặc mật khẩu";
                    Session["UserID"] = null;
                    return View(Login);
                }

            }
            catch
            {
                return View(Login);
            }
            return View();
        }

        public ActionResult ChangePassword()
        {
            if (Session["UserID"] == null)
            {
                int siteGuid = GetSiteGuid();
                
                return Redirect("/"+DefaultSiteGuidGetter()+"/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            olUrl = Request.UrlReferrer.AbsoluteUri != null ? Request.UrlReferrer.AbsoluteUri : "/"+DefaultSiteGuidGetter()+"/" + DefaultLanguageGetter() + "/User/SignIn";
            return View();
        }

        [HttpPost]
        public ActionResult ChangePassword(FormCollection values)
        {

            var change = new Models.Collection.ChangePassword();
            TryUpdateModel(change);

            try
            {

                string error = "";
                if (Models.UserModel.GetUerByID(int.Parse(Session["UserID"].ToString())).Password.Equals(change.Password))
                {
                    if (change.NewPassword.Equals(change.ConfirmPassword))
                    {
                        SCSService.Security_User user = Models.UserModel.GetUerByID(int.Parse(Session["UserID"].ToString()));
                        user.Password = change.NewPassword;
                        Models.UserModel.ChangePassword(user);
                    }
                    else
                        error = "Wrong vonfirm password!";
                }
                else
                {
                    error = "Wrong Password!";
                }
                ViewData["error"] = error;

                if (error == "")
                {
                    return Redirect(olUrl);
                }
            }
            catch
            {
                return View(change);
            }
            return View();
        }

        public ActionResult LogOut()
        {
            int siteGuid = GetSiteGuid();
            
            Session["UserID"] = null;
            return Redirect("/"+DefaultSiteGuidGetter()+"/" + DefaultLanguageGetter() + "/User/SignIn");
        }

        public ActionResult ForgotPassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ForgotPassword(FormCollection collection)
        {
            var forgot = new Models.Collection.ForgotCollection();
            TryUpdateModel(forgot);
            try
            {
                int userForgot = Models.UserModel.UserForgotPassword(forgot.UserName, forgot.Email) != null ? Models.UserModel.UserForgotPassword(forgot.UserName, forgot.Email).UserID : 0;
                if (userForgot > 0)
                {
                    //if (forgot.Agree)
                    //{
                    SCSService.BaseService baseSvc = new BaseService();
                    string newPassword = baseSvc.RandomString(6, true);
                    SCSService.Security_User user = Models.UserModel.UserForgotPassword(forgot.UserName, forgot.Email);
                    user.Password = newPassword;
                    baseSvc.SendEmailForgotPassword(user.Email, newPassword);

                    Models.UserModel.ChangePassword(user);
                    //}
                    //else
                    //{
                    //    ViewData["error"] = "You must agree to the terms!";
                    //    return View(forgot);
                    //}
                }

            }
            catch
            {
                return View(forgot);
            }
            return View();
        }

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.UserViewModels> viewData, string sortField)
        {

            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.UserViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListUsers(string UserName, string Email, byte? UserStatus)
        {
            int currentPage = 1;
            int pageSize = 2000;
            string sortField = "UserID";
            string sortDirection = "Desc";

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;


            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ListUsers(UserName, Email, UserStatus, currentPage, pageSize, sortField, sortDirection, null);


        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ListUsers(string UserName, string Email, byte? UserStatus, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction)
        {

            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 2000;
            }

            ViewData["currentPage"] = currentPage;

            //int TotalNumber = 0;
            int userIDLogin = 0;
            int priorityLogin = 0;

            if (Session["UserID"] != null)
            {
                userIDLogin = int.Parse(Session["UserID"].ToString());
                var user = Models.UserModel.GetUerByID(userIDLogin);
                var userRole = Models.UserModel.GetRoleByID(user != null ? user.RoleID ?? 0 : 0);
                priorityLogin = userRole != null ? userRole.Priority ?? 0 : 0;
            }

            var query = Models.UserModel.GetListUserByUserIDLogin(userIDLogin, priorityLogin, GetSiteGuid(),UserName, Email, UserStatus).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(SCSService.Security_User), "Security_User");
                var sortExpression = Expression.Lambda<Func<SCSService.Security_User, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Security_User>();    

            // Set up our ViewModel
            var viewModel = new SCS.Core.ViewModels.UserViewModels
            {
                UserItems = result,
                UserName = UserName,
                Email = Email,
                UserStatus = UserStatus
            };

            // Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
        }

        public ActionResult CreateUser()
        {
            var user = new Models.Collection.UserCollection();
            int userIDLogin = 0;
            int priorityLogin = 0;
            if (Session["UserID"] != null)
            {
                userIDLogin = int.Parse(Session["UserID"].ToString());
                var users = Models.UserModel.GetUerByID(userIDLogin);
                var userRole = Models.UserModel.GetRoleByID(user != null ? user.RoleID ?? 0 : 0);
                priorityLogin = userRole != null ? userRole.Priority ?? 0 : 0;
            }
            ViewData["ListUserRoleDrop"] = new SelectList(Models.UserModel.GetListRoleByPriority(priorityLogin,GetSiteGuid()), "RoleID", "RoleName");
            ViewData["IsAdd"] = true;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("UserDetails", user);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAddUser(FormCollection collection)
        {
            BaseService baseSvc = new BaseService();
            var user = new Models.Collection.UserCollection();
            TryUpdateModel(user);
            int userID = 0;
            try
            {
                //Create User
                SCSService.Security_User us = new Security_User();
                us.UserName = user.Email;
                if (user.Password != null && user.Password != string.Empty)
                {
                    us.Password = baseSvc.EnMD5(user.Password);
                }
                else
                {
                    us.Password = baseSvc.EnMD5("123456");     //Set default :123456
                }

                us.Email = user.Email;
                us.CreateDate = DateTime.Now;
                us.LastModified = null;
                us.UserStatus = 1;              
                us.UserDes = null;
                us.RoleID = user.RoleID;

                userID = Models.UserModel.CreateUser(us);
                if (userID > 0)
                {
                    ViewData["Result"] = "Create User Success!";

                    //Assign User for siteGuid
                    Security_Website_User swu = new Security_Website_User();
                    swu.CreateDate = DateTime.Now;
                    swu.SiteGuid = GetSiteGuid();
                    swu.UserID = userID;
                    swu.Notes = "User Create :" + int.Parse(Session["UserID"].ToString());

                    Models.UserModel.CreateWebsiteUser(swu);
                }
                
                return Redirect("ListUsers");
            }
            catch
            {
                return View("CreateUser", new Models.Collection.UserCollection());
            }
        }

        public ActionResult EditUser(int id)
        {
            //Only Edit with UserStatus =2
            var us = Models.UserModel.GetUerByID(id);
            var user = new Models.Collection.UserCollection();

            user.UserName = us.UserName;
            user.Email = us.Email;
            user.CreateDate = us.CreateDate;
            user.LastModified = us.CreateDate;
            user.UserStatus = us.UserStatus;
            user.UserDes = us.UserDes;
            user.RoleID = us.RoleID;
            user.Password = us.Password;
            user.UserID = us.UserID;

            ViewData["IsAdd"] = false;
            ViewData["Status"] = us.UserStatus;
            int userIDLogin = 0;
            int priorityLogin = 0;
            if (Session["UserID"] != null)
            {
                userIDLogin = int.Parse(Session["UserID"].ToString());
                var users = Models.UserModel.GetUerByID(userIDLogin);
                var userRole = Models.UserModel.GetRoleByID(users != null ? users.RoleID ?? 0 : 0);
                priorityLogin = userRole != null ? userRole.Priority ?? 0 : 0;
            }

            //if (Models.UserModel.GetListRoleByPriority(priorityLogin).Count <= 0)
            //{
            //    List<SelectListItem> ls = new List<SelectListItem>();
            //    ls.Add((new SelectListItem { Text = "User", Value = "1" }));

            //    ViewData["ListUserRoleDrop"] = ls;
            //}
            //else
            //{
                ViewData["ListUserRoleDrop"] = new SelectList(Models.UserModel.GetListRoleByPriority(priorityLogin,GetSiteGuid()), "RoleID", "RoleName", us.RoleID);
            //}
            

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("UserDetails", user);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEditUser(FormCollection collection)
        {
            var user = new Models.Collection.UserCollection();
            TryUpdateModel(user);

            try
            {

                //Update User
                SCSService.Security_User us = Models.UserModel.GetUerByID((int)user.UserID);
                us.UserName = user.UserName;
                us.Email = user.Email;
                us.LastModified = DateTime.Now;
                us.UserStatus = user.UserStatus;
                us.UserDes = user.UserDes;
                us.RoleID = user.RoleID;

                //Call Update method
                Models.UserModel.UpdateUser(us);

                return Redirect("ListUsers");
            }
            catch
            {
                return View("UserDetails", new Models.Collection.UserCollection());
            }

        }

        public ActionResult ProfileUser(int id)
        {
            var us = Models.UserModel.GetUerByID(id);
            var user = new Models.Collection.UserCollection();

            user.UserName = us.UserName;
            user.Email = us.Email;
            user.CreateDate = us.CreateDate;
            user.LastModified = us.CreateDate;
            user.UserStatus = us.UserStatus;
            user.UserDes = us.UserDes;
            user.RoleID = us.RoleID;

            ViewData["IsAdd"] = false;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("UserProfile", user);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEditProfileUser(FormCollection collection)
        {
            var user = new Models.Collection.UserCollection();
            TryUpdateModel(user);

            try
            {

                //Update User
                SCSService.Security_User us = Models.UserModel.GetUerByID((int)user.UserID);
                us.UserName = user.UserName;
                us.Email = user.Email;
                us.LastModified = DateTime.Now;
                us.UserStatus = user.UserStatus;
                us.UserDes = user.UserDes;
                //us.RoleID = user.RoleID;

                //Call Update method
                Models.UserModel.UpdateUser(us);

                return Redirect("");
            }
            catch
            {
                return View("", new Models.Collection.UserCollection());
            }

        }

        public ActionResult DeleteUser(int id, string returnUrl)
        {
            //ChangeUserStatus(id, 3);        //3 Is Status delete
            Models.UserModel.DeleteUser(id);

            return Redirect(returnUrl);
        }

        public ActionResult ChangeUserStatus(int? id, int? newstatus)
        {
            Models.UserModel.ChangeUserStatus(id, newstatus);

            string outStr = "" + newstatus;
            return Json(outStr);
        }

        public ActionResult ResetPassword(int? id)
        {
            var user = Models.UserModel.GetUerByID(id ?? 0);
            BaseService baseSvc = new BaseService();
            string newPassword = baseSvc.RandomString(6, true);
            SCSService.Security_User users = Models.UserModel.UserForgotPassword(user.UserName, user.Email);
            users.Password = newPassword;
            baseSvc.SendEmailForgotPassword(users.Email, newPassword);

            Models.UserModel.ChangePassword(users);

            string outStr = "Reset success!";
            return Json(outStr);
        }

        //Assign Permission
        public StringBuilder GetListUserPermissionBuilderCheckBox(int? id, List<SCSService.Security_Role_Permission> list)
        {
            StringBuilder sb = new StringBuilder();
            return ListUserPermissionBuilderCheckBox(ref sb, id, true, list);
        }

        public StringBuilder ListUserPermissionBuilderCheckBox(ref StringBuilder sb, int? id, bool root, List<SCSService.Security_Role_Permission> list)
        {

            List<SCSService.Security_Permission> listPer = Models.UserModel.GetListSecurityPermissionByParentID(id);
            if (root)
            {
                sb.Append("<ul id='navigation'>" + "Tree Permission");
            }
            else
            {
                sb.Append("<ul>");
            }

            foreach (var item in listPer)
            {
                bool Ischecked = false;
                foreach (var e in list)
                {
                    if (item.PerID == e.PerID)
                    {
                        Ischecked = true;
                    }
                }


                sb.Append("<li><input type='checkbox' " + (Ischecked == true ? "Checked" : String.Empty) + " id='" + item.PerID + "' onclick='checkUncheck(this);' />" + item.PerName + "");
                List<SCSService.Security_Permission> listChild = Models.UserModel.GetListSecurityPermissionByParentID(item.PerID);
                if (listChild.Count() > 0)
                {
                    ListUserPermissionBuilderCheckBox(ref sb, item.PerID, false, list);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }

        public StringBuilder GetListUserPermissionBuilder(int? id)
        {
            StringBuilder sb = new StringBuilder();
            return ListUserPermissionBuilder(ref sb, id, true);
        }

        public StringBuilder ListUserPermissionBuilder(ref StringBuilder sb, int? id, bool root)
        {
            List<SCSService.Security_Permission> listPer = Models.UserModel.GetListSecurityPermissionByParentID(id);
            if (root)
            {
                sb.Append("<ul id='navigation'>" + "Tree Permission");
            }
            else
            {
                sb.Append("<ul>");
            }

            foreach (var item in listPer)
            {
                sb.Append("<li>" + item.PerName + "");
                List<SCSService.Security_Permission> listChild = Models.UserModel.GetListSecurityPermissionByParentID(item.PerID);
                if (listChild.Count() > 0)
                {
                    ListUserPermissionBuilder(ref sb, item.PerID, false);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }

        public List<SCSService.Security_Permission> GetListUserPermissionDropBasic(int? id)
        {
            List<SCSService.Security_Permission> sb = new List<SCSService.Security_Permission>();
            return ListUserPermissionDropBasic(ref sb, id, true);
        }

        public List<SCSService.Security_Permission> ListUserPermissionDropBasic(ref List<SCSService.Security_Permission> sb, int? id, bool root)
        {
            List<SCSService.Security_Permission> listType = Models.UserModel.GetListSecurityPermissionByParentID(id);

            foreach (var item in listType)
            {
                if (!root)
                {
                    item.PerName = Models.UserModel.GetPermissionByID((int)item.ParentID).PerName + ">>" + item.PerName;

                    SCSService.Security_Permission pa = Models.UserModel.GetPermissionByID((int)id);
                    foreach (var itemStr in sb)
                    {
                        if (itemStr.PerID == pa.PerID)
                        {
                            if (itemStr.PerName.Contains(">>"))
                            {
                                int laststr = itemStr.PerName.LastIndexOf(">>") + 2;
                                string addStr = itemStr.PerName.Substring(0, laststr);
                                item.PerName = addStr + item.PerName;
                            }
                        }
                    }

                }


                sb.Add(item);
                List<SCSService.Security_Permission> listChild = Models.UserModel.GetListSecurityPermissionByParentID(item.PerID);
                if (listChild.Count() > 0)
                {
                    ListUserPermissionDropBasic(ref sb, item.PerID, false);
                }

            }

            return sb;
        }

        public ActionResult AssignPermission(int? id)
        {
            List<SCSService.Security_Role_Permission> listUserRolePermission = Models.UserModel.GetListSecurityRolePermissionByRoleID(id ?? 0);
            //id is RoleID
            ViewData["ListUserPermission"] = GetListUserPermissionBuilderCheckBox(null, listUserRolePermission);
            var assign = new Models.Collection.AssignPermissionCollection();
            assign.RoleID = id;
            assign.arrPerID = "";
            ViewData["RoleID"] = id;
            return View(assign);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAssignPermission(FormCollection collection)
        {
            var assign = new Models.Collection.AssignPermissionCollection();
            TryUpdateModel(assign);

            try
            {
                //Get List PerId assign for RoleID
                List<SCSService.Security_Role_Permission> listUserRolePermission = Models.UserModel.GetListSecurityRolePermissionByRoleID(assign.RoleID ?? 0);


                //Get List PerID select in checkbox
                string arrPerID = assign.arrPerID;

                if (arrPerID.EndsWith(","))
                {
                    int index = arrPerID.LastIndexOf(",");
                    arrPerID = arrPerID.Substring(0, index);
                }

                //Delete old PerID is assigned
                foreach (var item in listUserRolePermission)
                {
                    Models.UserModel.DeleteSecurityRolePermission(item.PerID, item.RoleID);
                }

                //Create New UserRolePermission
                var arr2 = arrPerID.Split(',');
                for (int i = 0; i < arr2.Length; i++)
                {
                    SCSService.Security_Role_Permission newUserRolePermission = new Security_Role_Permission();
                    newUserRolePermission.PerID = int.Parse(arr2[i]);
                    newUserRolePermission.RoleID = (int)assign.RoleID;
                    newUserRolePermission.CreateDate = DateTime.Now;

                    Models.UserModel.CreateSecurityRolePermission(newUserRolePermission);
                }

                return RedirectToAction("AssignPermission", new { id = assign.RoleID });
            }
            catch
            {
                return View("ListUserPermissions");
            }
        }

        public StringBuilder GetListModulePermissionBuilderCheckBox(List<SCSService.Security_Module_Permission> list,int? perID)
        {
            StringBuilder sb = new StringBuilder();
            return ListModulePermissionBuilderCheckBox(ref sb, list, perID);
        }

        public StringBuilder ListModulePermissionBuilderCheckBox(ref StringBuilder sb, List<SCSService.Security_Module_Permission> list,int? perID)
        {
            string result = "";
            string siteguid = "";
            string language = "";
            string str = Request.Url.PathAndQuery;
            var arr = str.Split('/');
                               

            if (Request.Url.Host == "localhost")
            {
                siteguid = arr[1];
                language = arr[2];

                result = "/" + siteguid + "/" + language + "/";
            }
            else
            {
                                   
                language = arr[1];
                result = "/" + language + "/";
            }

            List<SCSService.Config_Modul> listTab = Models.ConfigModel.GetListModulBySiteGuid(GetSiteGuid(),1);
            
            sb.Append("<ul id='navigation'>");

            foreach (var item in listTab)
            {
                bool Ischecked = false;
                foreach (var e in list)
                {
                  

                    if (item.ModulID == e.ModulID)
                    {
                        Ischecked = true;
                    }
                }


                sb.Append("<li><input type='checkbox' " + (Ischecked == true ? "Checked" : String.Empty) + " id='" + item.ModulID + "' onclick='checkUncheck(this);' />" + item.ModulName + "");
                sb.Append("<a href='" + result + "User/AssignPage/" + perID + "/" + item.ModulID + "' style='color:Blue'>" + " Assign Page " + "</a>");
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }

        public ActionResult AssignModule(int? id)
        {
            List<SCSService.Security_Module_Permission> listModulePermission = Models.UserModel.GetListModulePermissionByPerID(id ?? 0);
            //id is PerID
            ViewData["listModulePermission"] = GetListModulePermissionBuilderCheckBox(listModulePermission,id);
            var assign = new Models.Collection.AssignModulePermissonCollection();
            assign.PerID = id;
            assign.arrModulID = "";
            ViewData["PerID"] = id;
            return View(assign);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAssignModule(FormCollection collection)
        {
            var assign = new Models.Collection.AssignModulePermissonCollection();
            TryUpdateModel(assign);

            try
            {
                //Get List ModuleID assign for PerID
                List<SCSService.Security_Module_Permission> listModulePermission = Models.UserModel.GetListModulePermissionByPerID(assign.ModulID ?? 0);


                //Get List TabID select in checkbox
                string arrModulID = assign.arrModulID;

                if (arrModulID.EndsWith(","))
                {
                    int index = arrModulID.LastIndexOf(",");
                    arrModulID = arrModulID.Substring(0, index);
                }

                //Delete old ModuleID is assigned
                foreach (var item in listModulePermission)
                {
                    Models.UserModel.DeleteModulePermission(item.ModulID,item.PerID);
                }

                //Create New Module Permission
                var arr2 = arrModulID.Split(',');
                for (int i = 0; i < arr2.Length; i++)
                {
                    SCSService.Security_Module_Permission newModulePermission = new Security_Module_Permission();
                    newModulePermission.ModulID = int.Parse(arr2[i]);
                    newModulePermission.PerID = (int)assign.PerID;
                    newModulePermission.Note="user create :" + int.Parse(Session["UserID"].ToString());

                    Models.UserModel.CreateModulePermission(newModulePermission);
                }

                return RedirectToAction("AssignModule", new { id = assign.PerID });
            }
            catch
            {
                return View("ListUserPermissions");
            }
        }

        public StringBuilder GetListPagePermissionBuilderCheckBox(int? id,int? moduleID, List<SCSService.Security_Page_Permission> list)
        {
            StringBuilder sb = new StringBuilder();
            return ListPagePermissionBuilderCheckBox(ref sb, id, moduleID, true, list);
        }

        public StringBuilder ListPagePermissionBuilderCheckBox(ref StringBuilder sb, int? id,int? moduleID, bool root, List<SCSService.Security_Page_Permission> list)
        {

            List<SCSService.Config_Page> listPage = Models.ConfigModel.GetListPageByParentIDAndModuleID(id,moduleID);
            if (root)
            {
                sb.Append("<ul id='navigation'>" + "List Page in Module :"+Models.ConfigModel.GetModuleByID(moduleID??0).ModulName);
            }
            else
            {
                sb.Append("<ul>");
            }

            foreach (var item in listPage)
            {
                bool Ischecked = false;
                foreach (var e in list)
                {
                    if (item.PageID == e.PageID)
                    {
                        Ischecked = true;
                    }
                }


                sb.Append("<li><input type='checkbox' " + (Ischecked == true ? "Checked" : String.Empty) + " id='" + item.PageID + "' onclick='checkUncheck(this);' />" + item.PageName + "");
                List<SCSService.Config_Page> listChild = Models.ConfigModel.GetListPageByParentIDAndModuleID(item.PageID,moduleID);
                if (listChild.Count() > 0)
                {
                    ListPagePermissionBuilderCheckBox(ref sb, item.PageID,moduleID, false, list);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }

        public ActionResult AssignPage(int? id, int? proid)
        {
            List<SCSService.Security_Page_Permission> listPagePermission = Models.UserModel.GetListPagePermissionByPerID(id ?? 0);
            //id is PerID
            ViewData["listPagePermission"] = GetListPagePermissionBuilderCheckBox(null, proid, listPagePermission);
            var assign = new Models.Collection.AssignPagePermissionCollection();
            assign.PerID = id;
            assign.arrPageID = "";
            ViewData["PerID"] = id;
            return View(assign);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAssignPage(FormCollection collection)
        {
            var assign = new Models.Collection.AssignPagePermissionCollection();
            TryUpdateModel(assign);

            try
            {
                //Get List PageID assign for PerID
                List<SCSService.Security_Page_Permission> listPagePermission = Models.UserModel.GetListPagePermissionByPerID(assign.PerID ?? 0);


                //Get List TabID select in checkbox
                string arrPageID = assign.arrPageID;

                if (arrPageID.EndsWith(","))
                {
                    int index = arrPageID.LastIndexOf(",");
                    arrPageID = arrPageID.Substring(0, index);
                }

                //Delete old TabID is assigned
                foreach (var item in listPagePermission)
                {
                    Models.UserModel.DeletePagePermission(item.PageID,item.PerID);
                }

                //Create New PagePermission
                var arr2 = arrPageID.Split(',');
                for (int i = 0; i < arr2.Length; i++)
                {
                    SCSService.Security_Page_Permission newPagePermission = new Security_Page_Permission();
                    newPagePermission.PageID = int.Parse(arr2[i]);
                    newPagePermission.PerID = (int)assign.PerID;

                    Models.UserModel.CreatePagePermission(newPagePermission);
                }

                return RedirectToAction("AssignPage", new { id = assign.PerID });
            }
            catch
            {
                return View("ListUserPermissions");
            }
        }

        //User Role

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.UserRoleViewModels> viewData, string sortField)
        {

            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.UserRoleViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListUserRoles(string RoleName, byte? RoleStatus, int? Priority)
        {
            int currentPage = 1;
            int pageSize = 2000;
            string sortField = "RoleID";
            string sortDirection = "Desc";

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;


            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ListUserRoles(RoleName, RoleStatus, Priority, currentPage, pageSize, sortField, sortDirection, null);

        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ListUserRoles(string RoleName, byte? RoleStatus, int? Priority, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction)
        {

            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 2000;
            }

            ViewData["currentPage"] = currentPage;

           // int TotalNumber = 0;

            var query = Models.UserModel.GetListRole(RoleName, null, RoleStatus, Priority,GetSiteGuid()).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(SCSService.Security_Role), "Security_Role");
                var sortExpression = Expression.Lambda<Func<SCSService.Security_Role, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Security_Role>();  
                

            // Set up our ViewModel
            var viewModel = new SCS.Core.ViewModels.UserRoleViewModels
            {
                UserRoleItems = result,
                RoleName = RoleName,
                RoleStatus = RoleStatus,
                Priority = Priority
            };

            // Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
        }

        public ActionResult CreateUserRole()
        {
            var role = new Models.Collection.UserRoleCollection();

            ViewData["IsAdd"] = true;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("UserRoleDetails", role);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAddUserRole(FormCollection collection)
        {
            var role = new Models.Collection.UserRoleCollection();
            TryUpdateModel(role);
            int roleID = 0;
            try
            {
                //Create Template
                SCSService.Security_Role ro = new Security_Role();
                ro.RoleName = role.RoleName;
                ro.RoleDes = role.RoleDes;
                ro.RoleStatus = role.RoleStatus;
                ro.Priority = role.Priority;
                ro.UserCreated = int.Parse(Session["UserID"].ToString());
                ro.SiteGuidCreated = GetSiteGuid();

                roleID = Models.UserModel.CreateRole(ro);
                if (roleID > 0)
                {
                    ViewData["Result"] = "Create Role Success!";

                    //Assign Role for siteGuid
                    Sercurity_Website_Role swr = new Sercurity_Website_Role();
                    swr.SiteGuid = GetSiteGuid();
                    swr.RoleID = roleID;
                    swr.Description = "User create role :" + int.Parse(Session["UserID"].ToString());

                    Models.UserModel.CreateWebsiteRole(swr);
                }
                

                return Redirect("ListUserRoles");
            }
            catch
            {
                return View("CreateUserRole", new Models.Collection.UserRoleCollection());
            }

        }

        public ActionResult EditUserRole(int id)
        {
            var ro = Models.UserModel.GetRoleByID(id);
            var role = new Models.Collection.UserRoleCollection();

            role.RoleName = ro.RoleName;
            role.RoleDes = ro.RoleDes;
            role.RoleStatus = ro.RoleStatus;
            role.Priority = ro.Priority;
            role.RoleID = ro.RoleID;

            ViewData["IsAdd"] = false;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("UserRoleDetails", role);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEditUserRole(FormCollection collection)
        {
            var role = new Models.Collection.UserRoleCollection();
            TryUpdateModel(role);

            try
            {

                //Update UserRole
                SCSService.Security_Role ro = Models.UserModel.GetRoleByID((int)role.RoleID);
                ro.RoleName = role.RoleName;
                ro.RoleDes = role.RoleDes;
                ro.RoleStatus = role.RoleStatus;
                ro.Priority = role.Priority;

                //Call Update method
                Models.UserModel.UpdateRole(ro);

                return Redirect("ListUserRoles");
            }
            catch
            {
                return View("EditUserRole", new Models.Collection.UserRoleCollection());
            }

        }

        public ActionResult ChangeStatusUserRole(int? id, int? newstatus)
        {
            Models.UserModel.UpdateRoleStatus(id, newstatus);

            string outStr = "" + newstatus;
            return Json(outStr);
        }

        public ActionResult DeleteUserRole(int id, string returnUrl)
        {
            Models.UserModel.DeleteSecurityRole(id);

            return Redirect(returnUrl);
        }

        //User Permission

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.UserPermissionViewModels> viewData, string sortField)
        {

            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.UserPermissionViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListUserPermissions(string PerName, byte? PerStatus, int? ParentID)
        {
            int currentPage = 1;
            int pageSize = 20;
            string sortField = "PerID";
            string sortDirection = "Desc";

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            ViewData["ListPermission"] = GetListUserPermissionBuilder(null);

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ListUserPermissions(PerName, PerStatus, ParentID, currentPage, pageSize, sortField, sortDirection, null);


        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ListUserPermissions(string PerName, byte? PerStatus, int? ParentID, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction)
        {

            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 20;
            }

            ViewData["currentPage"] = currentPage;

            //int TotalNumber = 0;

            var query = Models.UserModel.GetListPermission(PerName, null, ParentID, PerStatus,GetSiteGuid()).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(SCSService.Security_Permission), "Security_Permission");
                var sortExpression = Expression.Lambda<Func<SCSService.Security_Permission, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Security_Permission>(); 

            // Set up our ViewModel
            var viewModel = new SCS.Core.ViewModels.UserPermissionViewModels
            {
                UserPermissionItems = result,
                PerName = PerName,
                PerStatus = PerStatus,
                ParentID = ParentID
            };

            // Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
        }

        public ActionResult CreateUserPermission()
        {
            var permission = new Models.Collection.UserPermissionCollection();
            ViewData["ListParent"] = new SelectList(GetListUserPermissionDropBasic(null), "PerID", "PerName");

            ViewData["IsAdd"] = true;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("UserPermissionDetails", permission);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAddUserPermission(FormCollection collection)
        {
            var permission = new Models.Collection.UserPermissionCollection();
            TryUpdateModel(permission);
            int perID = 0;
            try
            {
                //Create UserPermission
                SCSService.Security_Permission per = new SCSService.Security_Permission();
                per.PerName = permission.PerName;
                per.PerDes = permission.PerDes;
                per.PerStatus = permission.PerStatus;
                per.ParentID = permission.ParentID;
                per.UserCreated = int.Parse(Session["UserID"].ToString());
                per.SiteGuidCreated = GetSiteGuid();

                perID = Models.UserModel.CreateSecurityPermission(per);
                if (perID > 0)
                {
                    ViewData["Result"] = "Create Permission Success!";
                    //Assign Permission for SiteGuid
                    Security_Website_Permission swp = new Security_Website_Permission();
                    swp.SiteGuid = GetSiteGuid();
                    swp.PerID = perID;
                    swp.Description = "User create permission:" + int.Parse(Session["UserID"].ToString());
                }
                

                return Redirect("ListUserPermissions");
            }
            catch
            {
                return View("CreateUserPermission", new Models.Collection.UserPermissionCollection());
            }

        }

        public ActionResult EditUserPermission(int id)
        {
            var per = Models.UserModel.GetPermissionByID(id);
            var permission = new Models.Collection.UserPermissionCollection();

            permission.PerName = per.PerName;
            permission.PerDes = per.PerDes;
            permission.PerStatus = per.PerStatus;
            permission.ParentID = per.ParentID;
            permission.PerID = per.PerID;

            ViewData["IsAdd"] = false;
            ViewData["ListParent"] = new SelectList(GetListUserPermissionDropBasic(null), "PerID", "PerName");

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("UserPermissionDetails", permission);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEditUserPermission(FormCollection collection)
        {
            var permission = new Models.Collection.UserPermissionCollection();
            TryUpdateModel(permission);

            try
            {

                //Update UserPermission
                SCSService.Security_Permission per = Models.UserModel.GetPermissionByID((int)permission.PerID);
                per.PerName = permission.PerName;
                per.PerDes = permission.PerDes;
                per.PerStatus = permission.PerStatus;
                per.ParentID = permission.ParentID;

                //Call Update method
                Models.UserModel.UpdateSecurityPermission(per);

                return Redirect("ListUserPermissions");
            }
            catch
            {
                return View("EditUserPermission", new Models.Collection.UserPermissionCollection());
            }

        }

        public ActionResult ChangeStatusUserPermission(int? id, int? newstatus)
        {
            Models.UserModel.UpdatePermissionStatus(id, newstatus);

            string outStr = "" + newstatus;
            return Json(outStr);
        }

        public ActionResult DeleteUserPermission(int id, string returnUrl)
        {
            Models.UserModel.DeleteSecurityPermission(id);

            return Redirect(returnUrl);
        }
    }
}
